package cn.zyx.quartz.job;

import cn.zyx.order.domain.AdoptOrder;
import cn.zyx.order.service.IAdoptOrderService;
import cn.zyx.pay.constants.PayConstants;
import cn.zyx.pay.domain.PayBill;
import cn.zyx.pay.service.IPayBillService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class MainJob implements Job {

    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IAdoptOrderService adoptOrderService;

    /**
     * 我们自己的定时任务业务逻辑
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取定时器里面的数据 -- 支付单的唯一标识 -- 也是我们存在定时任务的唯一标识
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        Map<String, Object> params = (Map<String, Object>) jobDataMap.get("params");
        String unionPaySn = params.get("unionPaySn").toString();
        // 根据支付单号查询对应的支付单
        PayBill payBill = payBillService.loadByUnionPaySn(unionPaySn);
        // 定时的时间到了，修改支付单状态
        payBill.setState(-1); // 定时未支付
        payBill.setUpdateTime(new Date());
        payBillService.update(payBill);
        // 修改订单状态
        String businessType = payBill.getBusinessType();
        if (PayConstants.BUSINESS_TYPE_ADOPT.equals(businessType)) { // 领养订单
            Long businessKey = payBill.getBusinessKey();
            AdoptOrder adoptOrder = adoptOrderService.getById(businessKey);
            adoptOrder.setState(-1);         // 定时未支付
            adoptOrderService.update(adoptOrder);
        }
    }
}
